package com.bwhk.splitdata.task;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.bwhk.splitdata.split.MessageObject;
import com.bwhk.splitdata.task.model.ItemFreq;
import com.bwhk.splitdata.utils.JsonUtil;

@Component
public class SendMqJob  implements Job{
   private static Logger logger = LoggerFactory.getLogger(SendMqJob.class);     
   @Autowired  
   private AmqpTemplate rabbitTemplate; 
   @Autowired
   private JdbcTemplate jdbcTemplate;
   
   private String convertDate(Date date) {
	   	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	   	return sdf.format(date);
   }
   @Override  
   public void execute(JobExecutionContext context) throws JobExecutionException {  
        //取得job详情  
        JobDetail jobDetail = context.getJobDetail();     
        // 取得job名称  
        String jobName = jobDetail.getKey().getName();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        logger.info(jobName+":{itemFreq_id:"+jobDataMap.get("itemFreq_id")+",itemFreq_descr:"+jobDataMap.get("itemFreq_descr")+"}");
		String sql = "select it.id,it.watch_item_id,it.status,its.item_name,its.item_desc,its.value_type from iyw_watch_item_sum its,iyw_watch_item it where its.id = it.item_sum_id and its.freq_id = ? ";
		List<MessageObject> moList = jdbcTemplate.query(sql,new Object[]{jobDataMap.get("itemFreq_id")}, new RowMapper<MessageObject>() {
		    public MessageObject mapRow(ResultSet rs, int rowNum) throws SQLException {
		    	MessageObject mo = new MessageObject();
		    	mo.setId(rs.getLong("ID"));
		    	mo.setWatch_item_id(rs.getString("watch_item_id"));
		    	mo.setStatus(rs.getString("status"));
		    	mo.setItemName(rs.getString("ITEM_NAME"));
		    	mo.setItemDesc(rs.getString("ITEM_DESC"));
		    	mo.setValueType(rs.getString("VALUE_TYPE"));
		        return mo;  
		    }  
		});
		for (int i=0;i<moList.size();i++) {
			MessageObject mo = moList.get(i);
			String json = JsonUtil.toJson(mo);
			logger.info(json);
			this.rabbitTemplate.convertAndSend("split_work", json);
		}
   }  

}
